import { useDispatch } from 'react-redux';
import { makeUpdateFn } from '../utils';
import { ITestState, useRootState } from '..';
import { testSlice } from '.';

// 更新函数
export const updateTest = makeUpdateFn<ITestState>(testSlice.actions);

// 获取test的rootState
export function useTestRootState(): ITestState {
  return useRootState('test');
}

// 获取某一项state并且通过hooks来更新我们的state
export function useTestState<T extends keyof ITestState>(key: T) {
  const rootState = useTestRootState();

  // 某一项的值
  const value = rootState[key];

  const dispatch = useDispatch();
  const setValue = (val: ITestState[T]) => {
    updateTest({ [key]: val }, dispatch);
  };

  return [value, setValue] as [ITestState[T], typeof setValue];
}
